package com.nexfra.bbssys.bbs.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.nexfra.bbssys.bbs.service.BbsGeneralBoardService;
import com.nexfra.bbssys.common.Constants;
import com.nexfra.bbssys.common.domain.AttachFile;
import com.nexfra.bbssys.common.domain.User;
import com.nexfra.bbssys.common.service.CommonService;
import com.nexfra.bbssys.common.utils.FileManagement;
import com.nexfra.bbssys.common.utils.Paginator;
import com.nexfra.bbssys.common.utils.StringUtil;

@Controller
@RequestMapping(value = "/bbs/bbsGeneralBoard") 
public class BbsGeneralBoardController {
	private static final Logger logger = LoggerFactory.getLogger(BbsGeneralBoardController.class);
	
	@Autowired
	BbsGeneralBoardService service;

	@Autowired
	CommonService commonService;

	/**
	 * 게시판목록을 조회한다.
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String selectGeneralBoardList(
			@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model)  throws Exception {
		logger.info("######################################################");
		logger.info("     selectGeneralBoardList ");
		logger.info("######################################################");		
		logger.info("bef requestParam:"+params.toString());
		// RedirectView에서 리다이렉트된 경우 FlashMap에 저장되어 전달된 값을 가져온다.  
	    Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);  
	    if(flashMap !=null) {  
	    	params.put("page_no", (String)flashMap.get("page_no"));    
	    }  
	    logger.info("aft requestParam:"+params.toString());
	    
		long totalRowsCount = service.selectGeneralBoardListCount(params); //  전체count
		logger.info("totalRowsCount:" + totalRowsCount);
		
		
		int pageNo = Integer.parseInt(StringUtils.defaultString(params.get("page_no"),"1"));
		
		Paginator paginator = new Paginator(pageNo, totalRowsCount);
		paginator.setPageProperties();
		
		// 게시물리스트 조회
		params.put("start_row", paginator.getStartRow()+"");
		params.put("end_row", paginator.getEndRow()+"");
		List<Map<String, Object>> list = service.selectGeneralBoardList(params);
		logger.info("list:" + list);
/*
//test
		// 전체rows
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(long i=startRow; i<= endRow; i++) {
			Map<String,Object> item = new HashMap<String,Object>();
			item.put("ATCL_ID", i);
			item.put("THREAD", "THREAD"+i);
			item.put("PARENT_ATCL_ID", "PARENT_ATCL_ID"+i);
			item.put("DEPTH", "1");
			item.put("ORDER_SEQ", "1");
			item.put("REPLY_YN", "N");
			item.put("SUBJECT", "SUBJECT"+(i));
			item.put("CONTENTS", "CONTENTS"+(i));
			item.put("READ_CNT", 1);
			item.put("RCMD_CNT", 1);
			item.put("MEM_ID", "admin");
			item.put("MEM_NAME", "admin");
			item.put("EMAIL_ID", "admin@gmail.com");
			item.put("PASSWD", "123");
			item.put("DEL_YN", "N");
			item.put("REG_IP", "192.168.0.1");
			item.put("VIEW_STDT", "20130101");
			item.put("VIEW_EDDT", "99991231");
			item.put("ATCH_EXIST_YN", "Y");
			item.put("CREATE_DATE", "20130101");
			list.add(item);
		}
//test end		
*/
		model.addAttribute("paginator", paginator);
		model.addAttribute("params", params);
		model.addAttribute("list", list);
		return "/bbssys/bbs/bbsGeneralBoardList";
	}	

	/**
	 * 게시글을 등록한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/regist")
	@Transactional(rollbackFor = Exception.class)
	public String insertGeneralBoard(@RequestParam HashMap<String, String> params
			,@RequestParam("attachFile[]") List<MultipartFile> attachFiles
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     insertGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
		logger.info("attachFiles:"+attachFiles);	
		
		// file 업로드
		/*MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest)request;
		List<AttachFile> uploadedAttachFiles = null;
		
		if(attachFiles != null && attachFiles.size() > 0 ) {
			Map<String, MultipartFile> filesMap = new HashMap<String, MultipartFile>(); 
			int i=0;
			for(MultipartFile mpf: attachFiles) {	
				logger.info("=============[attach file]===================");
				logger.info(""+mpf.getContentType());
				logger.info(""+mpf.getOriginalFilename());
				logger.info(""+mpf.getSize());
				logger.info(""+mpf.getName());
				
				filesMap.put("attachFiles["+(i++)+"]", mpf);
			}
			
			logger.info("filesMap:"+filesMap);	
//@TODO BBS경로 외부로 빼기			
			uploadedAttachFiles = FileManagement.uploadFile(mpRequest, "BBS", filesMap, null); // 저장될 위치,MultipartFile 리스트,저장될 파일이름,제한할 파일사이즈(10485760B=>10MB)				
		
			logger.info(uploadedAttachFiles + "");
		}*/
		// 파일 업로드
		List<AttachFile> uploadedAttachFiles = null;
		if(attachFiles != null && attachFiles.size() > 0 ) {
			uploadedAttachFiles = uploadFiles((MultipartHttpServletRequest)request, attachFiles);
		}
		logger.info(uploadedAttachFiles + "");
		
		// 파라미터 세팅
		String atclId = service.selectSeqAtclId(); // 게시글id 채번
		String thread = service.selectSeqThread(); // thread 채번
		String parentAtclId = null; // 부모글id 
		String depth = "0"; // depth 
		String orderSeq = "1"; // 소트순서 
		String replyYn = "N"; // 답변여부 
		String readCnt = "0"; // 조회수 
		String rcmdCnt = "0"; // 추천수 
		String delYn = "N"; // 삭제여부 
		String regIp = request.getRemoteAddr(); // 등록지IP 
		String atchExistYn = (uploadedAttachFiles != null && uploadedAttachFiles.size() > 0? "Y":"N");
		params.put("atcl_id", atclId);
		params.put("thread", thread);
		params.put("parent_atcl_id", parentAtclId);
		params.put("depth", depth);
		params.put("order_seq", orderSeq);
		params.put("reply_yn", replyYn);
		params.put("read_cnt", readCnt);
		params.put("rcmd_cnt", rcmdCnt);
		params.put("del_yn", delYn);
		params.put("reg_ip", regIp);
		params.put("atch_exist_yn", atchExistYn);
		params.put("view_stdt", StringUtil.replace((String)params.get("view_stdt" ), "/", ""));
		params.put("view_eddt", StringUtil.replace((String)params.get("view_eddt" ), "/", ""));
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_KEY);
		params.put("mem_id", user.getUserId());
		params.put("mem_name", user.getUserName());
		params.put("user_id", user.getUserId());		
		
		// 첨부파일 db등록
		if(uploadedAttachFiles != null && uploadedAttachFiles.size() > 0) {
			HashMap<String,String> paramsAtch = null;
			
			for(AttachFile file: uploadedAttachFiles) {
				paramsAtch = new HashMap<String,String>();
				paramsAtch.put("atch_id", service.selectSeqAtchId());
				paramsAtch.put("atch_file_nm", file.getOriginFileName());
				paramsAtch.put("atch_file_alias", file.getAliasFileName());
				paramsAtch.put("atch_full_path", file.getFileTotalPath());
				paramsAtch.put("atch_file_size", file.getFileSize());
				paramsAtch.put("atch_ext", file.getFileExtension());
				
				paramsAtch.put("bbs_id", params.get("bbs_id"));
				paramsAtch.put("atcl_id", atclId);
				paramsAtch.put("cmmt_id", null);
				paramsAtch.put("user_id", user.getUserId());	
				
				service.insertAtchFile(paramsAtch);		
			}
		}	
		
		// 게시글 등록
		service.insertGeneralBoard(params);
		
		// 태그 등록
		String[] tagIds = StringUtils.split(params.get("tag_id"), ",");
		if(tagIds != null && tagIds.length > 0) {
			for(String tagId: tagIds) {
				if(!"".equals(StringUtils.trim(tagId))) {
					params.put("tag_id", StringUtils.trim(tagId));
					service.insertAtclTagId(params);
				}
			}
		}
		return "redirect:/bbs/bbsGeneralBoard/list?bbs_id="+params.get("bbs_id");									
	 }

	/**
	 * 답변글을 등록한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/reply")
	@Transactional(rollbackFor = Exception.class)
	public String insertReplyGeneralBoard(@RequestParam HashMap<String, String> params
			,@RequestParam("attachFile[]") List<MultipartFile> attachFiles
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     insertReplyGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
		logger.info("attachFiles:"+attachFiles);	
		
		// file 업로드
		/*MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest)request;
		List<AttachFile> uploadedAttachFiles = null;
		
		if(attachFiles != null && attachFiles.size() > 0 ) {
			Map<String, MultipartFile> filesMap = new HashMap<String, MultipartFile>(); 
			int i=0;
			for(MultipartFile mpf: attachFiles) {	
				logger.info("=============[attach file]===================");
				logger.info(""+mpf.getContentType());
				logger.info(""+mpf.getOriginalFilename());
				logger.info(""+mpf.getSize());
				logger.info(""+mpf.getName());
				
				filesMap.put("attachFiles["+(i++)+"]", mpf);
			}
			
			logger.info("filesMap:"+filesMap);	
			uploadedAttachFiles = FileManagement.uploadFile(mpRequest, "BBS", filesMap, null); // 저장될 위치,MultipartFile 리스트,저장될 파일이름,제한할 파일사이즈(10485760B=>10MB)				
			
			logger.info(uploadedAttachFiles + "");
		}*/
		// 파일 업로드
		List<AttachFile> uploadedAttachFiles = null;
		if(attachFiles != null && attachFiles.size() > 0 ) {
			uploadedAttachFiles = uploadFiles((MultipartHttpServletRequest)request, attachFiles);
		}
		logger.info(uploadedAttachFiles + "");
		
		// 파라미터 세팅
		String atclId = service.selectSeqAtclId(); // 글id 채번
		String thread = params.get("thread"); // 부모글의 thread
		String parentAtclId = params.get("atcl_id"); // 부모글id 
		String depth = (Integer.parseInt(params.get("depth"))+1)+""; // 부모글의 depth+1
		String orderSeq = (Integer.parseInt(params.get("order_seq"))+1)+""; // 부모글의 order_seq+1 
		String pOrderSeq = params.get("order_seq"); // 부모글의 order_seq
///////////////////////////////////////////////////
		String replyYn = "Y"; // 답변여부 
		String readCnt = "0"; // 조회수 
		String rcmdCnt = "0"; // 추천수 
		String delYn = "N"; // 삭제여부 
		String regIp = request.getRemoteAddr(); // 등록지IP 
		String atchExistYn = (uploadedAttachFiles != null && uploadedAttachFiles.size() > 0? "Y":"N");
		params.put("atcl_id", atclId);
		params.put("thread", thread);
		params.put("parent_atcl_id", parentAtclId);
		params.put("depth", depth);
		params.put("order_seq", orderSeq);
		params.put("reply_yn", replyYn);
		params.put("read_cnt", readCnt);
		params.put("rcmd_cnt", rcmdCnt);
		params.put("del_yn", delYn);
		params.put("reg_ip", regIp);
		params.put("atch_exist_yn", atchExistYn);
		params.put("view_stdt", StringUtil.replace((String)params.get("view_stdt" ), "/", ""));
		params.put("view_eddt", StringUtil.replace((String)params.get("view_eddt" ), "/", ""));
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_KEY);
		params.put("mem_id", user.getUserId());
		params.put("mem_name", user.getUserName());
		params.put("user_id", user.getUserId());		
		
		// 첨부파일 db등록
		if(uploadedAttachFiles != null && uploadedAttachFiles.size() > 0) {
			HashMap<String,String> paramsAtch = null;
			
			for(AttachFile file: uploadedAttachFiles) {
				paramsAtch = new HashMap<String,String>();
				paramsAtch.put("atch_id", service.selectSeqAtchId());
				paramsAtch.put("atch_file_nm", file.getOriginFileName());
				paramsAtch.put("atch_file_alias", file.getAliasFileName());
				paramsAtch.put("atch_full_path", file.getFileTotalPath());
				paramsAtch.put("atch_file_size", file.getFileSize());
				paramsAtch.put("atch_ext", file.getFileExtension());
				
				paramsAtch.put("bbs_id", params.get("bbs_id"));
				paramsAtch.put("atcl_id", atclId);
				paramsAtch.put("cmmt_id", null);
				paramsAtch.put("user_id", user.getUserId());	
				
				service.insertAtchFile(paramsAtch);		
			}
		}	
		
		// 같은 thread내 order_seq 업데이트
		//   : 부모글의 order_seq보다 큰 게시물의 order_seq를 모두 1만큼 증가시킨다. 
		params.put("p_order_seq", pOrderSeq);
		service.updateOrderSeqGeneralBoard(params);
		
		// 답변글 등록
		service.insertGeneralBoard(params);
		
		redirectAttributes.addFlashAttribute("page_no", params.get("page_no"));  
		return "redirect:/bbs/bbsGeneralBoard/list?bbs_id="+params.get("bbs_id");									
	}
	
	/**
	 * 댓글을 등록한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/registComment")
	@Transactional(rollbackFor = Exception.class)
	public String insertCommentGeneralBoard(@RequestParam HashMap<String, String> params
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     insertCommentGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
				
		// 파라미터 세팅
		String atclId = params.get("atcl_id");
		String cmmtId = service.selectSeqCmmtId(); // 댓글id 채번
		String thread = service.selectSeqCmmtThread(); // 댓글thread 채번
		String parentCmmtId = params.get("cmmt_id"); 
		String depth = StringUtils.defaultString(params.get("depth"),"0");
		String orderSeq = Integer.parseInt(StringUtils.defaultString(params.get("order_seq"),"0"))+1 + ""; 
		String pOrderSeq = Integer.parseInt(StringUtils.defaultString(params.get("order_seq"),"0"))+"";
///////////////////////////////////////////////////
		String replyYn = "".equals(StringUtils.defaultString(parentCmmtId,""))? "N":"Y"; // 답변여부 
		String rcmdCnt = "0"; // 추천수 
		String delYn = "N"; // 삭제여부 
		String regIp = request.getRemoteAddr(); // 등록지IP 
		String atchExistYn = "N";
		
		params.put("atcl_id", atclId);
		params.put("cmmt_id", cmmtId);
		params.put("thread", thread);
		params.put("parent_cmmt_id", parentCmmtId);
		params.put("depth", depth);
		params.put("order_seq", orderSeq);
		params.put("reply_yn", replyYn);
		params.put("rcmd_cnt", rcmdCnt);
		params.put("del_yn", delYn);
		params.put("reg_ip", regIp);
		params.put("atch_exist_yn", atchExistYn);
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_KEY);
		params.put("user_id", user.getUserId());		
		
		// 같은 thread내 order_seq 업데이트
		//   : 부모글의 order_seq보다 큰 게시물의 order_seq를 모두 1만큼 증가시킨다. 
		//params.put("p_order_seq", pOrderSeq);
		//service.updateCommentOrderSeqGeneralBoard(params);
		
		// 댓글 등록
		service.insertCommentGeneralBoard(params);

		// 댓글 조회
		List<Map<String, Object>> listCmmt = service.selectGeneralBoardCmmt(params);
		logger.info("listCmmt:" + listCmmt);
		
		model.addAttribute("listCmmt", listCmmt);
		return "/bbssys/bbs/bbsGeneralBoardFormComment";
	}	
	
	/**
	 * 답댓글을 등록한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/replyComment")
	@Transactional(rollbackFor = Exception.class)
	public String replyCommentGeneralBoard(@RequestParam HashMap<String, String> params
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     replyCommentGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
  
		// 파라미터 세팅
		String atclId = params.get("atcl_id");
		String cmmtId = service.selectSeqCmmtId(); // 댓글id 채번
		String thread = params.get("thread"); // thread
		String parentCmmtId = params.get("cmmt_id"); 
		String depth = (Integer.parseInt(StringUtils.defaultString(params.get("depth"),"0")) + 1) + "";
		String orderSeq = Integer.parseInt(StringUtils.defaultString(params.get("order_seq"),"0"))+1 + ""; 
		String pOrderSeq = params.get("order_seq");
///////////////////////////////////////////////////
		String replyYn = "Y"; // 답변여부 
		String rcmdCnt = "0"; // 추천수 
		String delYn = "N"; // 삭제여부 
		String regIp = request.getRemoteAddr(); // 등록지IP 
		String atchExistYn = "N";
		
		params.put("atcl_id", atclId);
		params.put("cmmt_id", cmmtId);
		params.put("thread", thread);
		params.put("parent_cmmt_id", parentCmmtId);
		params.put("depth", depth);
		params.put("order_seq", orderSeq);
		params.put("reply_yn", replyYn);
		params.put("rcmd_cnt", rcmdCnt);
		params.put("del_yn", delYn);
		params.put("reg_ip", regIp);
		params.put("atch_exist_yn", atchExistYn);
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_KEY);
		params.put("user_id", user.getUserId());		
		
		// 같은 thread내 order_seq 업데이트
		//   : 부모글의 order_seq보다 큰 게시물의 order_seq를 모두 1만큼 증가시킨다. 
		params.put("p_order_seq", pOrderSeq);
		service.updateCommentOrderSeqGeneralBoard(params);
		
		// 답댓글 등록
		service.insertCommentGeneralBoard(params);

		// 댓글 조회
		List<Map<String, Object>> listCmmt = service.selectGeneralBoardCmmt(params);
		logger.info("listCmmt:" + listCmmt);
		
		model.addAttribute("listCmmt", listCmmt);
		return "/bbssys/bbs/bbsGeneralBoardFormComment";
	}		
	
	/**
	 * 댓글을 삭제한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/deleteComment")
	@Transactional(rollbackFor = Exception.class)
	public String deleteCommentGeneralBoard(@RequestParam HashMap<String, String> params
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     deleteCommentGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
				
		// 댓글 삭제
		service.deleteCommentGeneralBoard(params);
				
		// 댓글 조회
		List<Map<String, Object>> listCmmt = service.selectGeneralBoardCmmt(params);
		logger.info("listCmmt:" + listCmmt);
		
		model.addAttribute("listCmmt", listCmmt);
		return "/bbssys/bbs/bbsGeneralBoardFormComment";	
	 }	
	
	/**
	 * 파일을 업로드한다.
	 * 
	 * @param model
	 * @return
	 */	
	public List<AttachFile> uploadFiles(MultipartHttpServletRequest mprequest, List<MultipartFile> attachFiles) 
			throws Exception {
		Map<String, MultipartFile> filesMap = new HashMap<String, MultipartFile>(); 
		int i=0;
		for(MultipartFile mpf: attachFiles) {	
			logger.info("=============[attach file]===================");
			logger.info(""+mpf.getContentType());
			logger.info(""+mpf.getOriginalFilename());
			logger.info(""+mpf.getSize());
			logger.info(""+mpf.getName());
			
			filesMap.put("attachFiles["+(i++)+"]", mpf);
		}
		
		logger.info("filesMap:"+filesMap);	
		List<AttachFile> uploadedAttachFiles = FileManagement.uploadFile(mprequest, "BBS", filesMap, null); // 저장될 위치,MultipartFile 리스트,저장될 파일이름,제한할 파일사이즈(10485760B=>10MB)				
		
		return uploadedAttachFiles;
	}
	
	/**
	 * 게시글을 수정한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/update")
	@Transactional(rollbackFor = Exception.class)
	public String updateGeneralBoard(@RequestParam HashMap<String, String> params
			,@RequestParam("attachFile[]") List<MultipartFile> attachFiles
			,@RequestParam(value="chkAttachDel[]", required=false) String[] chkAttachDel
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     updateGeneralBoard ");
		logger.info("######################################################");
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
		logger.info("attachFiles:"+attachFiles);	
		logger.info("chkAttachDel:"+chkAttachDel);	

		// 파일 업로드
		List<AttachFile> uploadedAttachFiles = null;
		if(attachFiles != null && attachFiles.size() > 0 ) {
			uploadedAttachFiles = uploadFiles((MultipartHttpServletRequest)request, attachFiles);
		}
		logger.info(uploadedAttachFiles + "");

		// 파일 삭제
		deleteFiles(chkAttachDel);

		String atchExistYn = service.selectGeneralBoardAtchCount(params) > 0? "Y":"N";
		params.put("atch_exist_yn", atchExistYn);
		params.put("view_stdt", StringUtil.replace((String)params.get("view_stdt" ), "/", ""));
		params.put("view_eddt", StringUtil.replace((String)params.get("view_eddt" ), "/", ""));
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_KEY);
		params.put("mem_id", params.get("mem_id"));
		params.put("mem_name", params.get("mem_name"));
		params.put("user_id", user.getUserId());		
		
		// 첨부파일 db등록
		if(uploadedAttachFiles != null && uploadedAttachFiles.size() > 0) {
			HashMap<String,String> paramsAtch = null;
			
			for(AttachFile file: uploadedAttachFiles) {
				paramsAtch = new HashMap<String,String>();
				paramsAtch.put("atch_id", service.selectSeqAtchId());
				paramsAtch.put("atch_file_nm", file.getOriginFileName());
				paramsAtch.put("atch_file_alias", file.getAliasFileName());
				paramsAtch.put("atch_full_path", file.getFileTotalPath());
				paramsAtch.put("atch_file_size", file.getFileSize());
				paramsAtch.put("atch_ext", file.getFileExtension());
				
				paramsAtch.put("bbs_id", params.get("bbs_id"));
				paramsAtch.put("atcl_id", params.get("atcl_id"));
				paramsAtch.put("cmmt_id", null);
				paramsAtch.put("user_id", user.getUserId());	
				
				service.insertAtchFile(paramsAtch);		
			}
		}	
		
		// 게시글 수정
		service.updateGeneralBoard(params);
		
		//return "forward:/bbs/bbsGeneralBoard/list?bbs_id="+params.get("bbs_id");
		//====>
		redirectAttributes.addFlashAttribute("page_no", params.get("page_no"));  
		return "redirect:/bbs/bbsGeneralBoard/list?bbs_id="+params.get("bbs_id");									
	}
	
	/**
	 * 파일을 삭제한다.(삭제플래그 이용)
	 * 
	 * @param model
	 * @return
	 */	
	public void deleteFiles(String[] atchIds) throws Exception {
		HashMap<String,String> params = null;

		if(atchIds != null && atchIds.length > 0) {
			params = new HashMap<String,String>();
			params.put("atch_group", "BBS");
			
			// db에서 삭제 플래그값을 Y로 변경한다.
			for(String atchId: atchIds) {
				params.put("atch_id", atchId);
				service.deleteGeneralBoardAtch(params);
			}
		}
	}
	
	/**
	 * 게시글을 삭제한다.
	 * 
	 * @param model
	 * @return
	 */	
	@RequestMapping(value = "/delete")
	@Transactional(rollbackFor = Exception.class)
	public String deleteGeneralBoard(@RequestParam HashMap<String, String> params
			,@RequestParam(value="atchIds[]", required=false) String[] atchIds
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request, HttpServletResponse response
			,ModelMap model) throws Exception {
		logger.info("######################################################");
		logger.info("     deleteGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
		logger.info("atchIds:"+atchIds);	

		// 파일 삭제
		deleteFiles(atchIds);
		
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_KEY);
		params.put("user_id", user.getUserId());	
		
		// 게시글 삭제
		service.deleteGeneralBoard(params);
				
		redirectAttributes.addFlashAttribute("page_no", params.get("page_no"));  
		return "redirect:/bbs/bbsGeneralBoard/list?bbs_id="+params.get("bbs_id");		
	 }	
	
	/**
	 * 게시판 폼(신규) 페이지로 이동한다.
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/form", params="action_name=NEW_FORM")
	public String formNewGeneralBoard(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response, ModelMap model)  
				throws Exception {
		logger.info("######################################################");
		logger.info("     formNewGeneralBoard ");
		logger.info("######################################################");			
		model.addAttribute("params", params);
		return "/bbssys/bbs/bbsGeneralBoardForm";
	}	

	/**
	 * 게시판 폼(상세/답글/수정) 페이지로 이동한다.
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/form", params="action_name=DETAIL_FORM")
	public String formDetailGeneralBoard(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response, ModelMap model)  
					throws Exception {
		logger.info("######################################################");
		logger.info("     formDetailGeneralBoard ");
		logger.info("######################################################");			
		logger.info("requestParam:"+params.toString());
		logger.info("requestParameterMap:"+request.getParameterMap());
		
		 // 상세보기일 경우 조회수를 업데이트한다.
		if("DETAIL_FORM".equals(params.get("action_name"))) {
			HttpSession session = request.getSession();
			User user = (User)session.getAttribute(Constants.USER_KEY);
			params.put("user_id", user.getUserId());
			
			service.updateReadCntGeneralBoard(params);
		}
		
		// 게시글 조회
		Map<String, Object> item = service.selectGeneralBoard(params);
		logger.info("item:" + item);
		
		if("DETAIL_FORM".equals(params.get("action_name")) || "UPDATE_FORM".equals(params.get("action_name"))) {
			// 댓글 조회
			List<Map<String, Object>> listCmmt = service.selectGeneralBoardCmmt(params);
			logger.info("listCmmt:" + listCmmt);
			// 첨부파일 조회
			List<Map<String, Object>> listAtch = service.selectGeneralBoardAtch(params);
			logger.info("listAtch:" + listAtch);
			
			model.addAttribute("listCmmt", listCmmt);
			model.addAttribute("listAtch", listAtch);
		}
		
		model.addAttribute("params", params);
		model.addAttribute("item", item);
		return "/bbssys/bbs/bbsGeneralBoardForm";
	}	
	

	/**
	 * 게시판 폼(수정) 페이지로 이동한다.
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/form", params="action_name=UPDATE_FORM")
	public String formUpdateGeneralBoard(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response, ModelMap model)  
					throws Exception {
		logger.info("######################################################");
		logger.info("     formUpdateGeneralBoard ");
		logger.info("######################################################");			
		
		return formDetailGeneralBoard(params,request,response,model);
	}	
	
	
	/**
	 * 게시판 폼(답글) 페이지로 이동한다.
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/form", params="action_name=REPLY_FORM")
	public String formReplyGeneralBoard(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response, ModelMap model)  
					throws Exception {
		logger.info("######################################################");
		logger.info("     formReplyGeneralBoard ");
		logger.info("######################################################");			
		
		return formDetailGeneralBoard(params,request,response,model);
	}	
}